//
//  QNCPDeviceManager+Addition.m
//  QNCPDeviceModule
//
//  Created by yolanda on 2025/6/9.
//

#import "QNCPDeviceManager+Addition.h"


#pragma mark - QNCPDeviceManager (Log)
@implementation QNCPDeviceManager (Log)

- (void)deviceLogMessage:(NSString *)message {
    if (QNCentralManager.logPrefix) {
        [self.centralManager logMessage:[[QNCPDeviceLogCode stringByAppendingString:@": "] stringByAppendingString:message]];
    }else {
        [self.centralManager logMessage:message];
    }
}
@end


@implementation QNCPDeviceManager (Addition)

static char QNCPDeviceManagerQnCentralManagerKey;
static char QNCPDeviceManagerScaleDeviceKey;
static char QNCPDeviceManagerDelegateKey;

- (void)setCentralManager:(QNCentralManager *)centralManager {
    objc_setAssociatedObject(self, &QNCPDeviceManagerQnCentralManagerKey, centralManager, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (QNCentralManager *)centralManager {
    return objc_getAssociatedObject(self, &QNCPDeviceManagerQnCentralManagerKey);
}

- (void)setScaleDevice:(QNCPDevice *)scaleDevice {
    objc_setAssociatedObject(self, &QNCPDeviceManagerScaleDeviceKey, scaleDevice, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (QNCPDevice *)scaleDevice {
    return objc_getAssociatedObject(self, &QNCPDeviceManagerScaleDeviceKey);
}

- (void)setDelegates:(NSHashTable<id<QNCPDeviceDelegate>> *)delegates {
    objc_setAssociatedObject(self, &QNCPDeviceManagerDelegateKey, delegates, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSHashTable<id<QNCPDeviceDelegate>> *)delegates {
    return objc_getAssociatedObject(self, &QNCPDeviceManagerDelegateKey);
}

- (void)delegateSelectorOnMainThread:(SEL)selector callBlock:(void (^)(id<QNCPDeviceDelegate> _Nonnull))block {
    if ([NSThread isMainThread]) {
        NSArray *temp = [self.delegates copy];
        NSEnumerator *enumerator = [temp objectEnumerator];
        id<QNCPDeviceDelegate> delegate = nil;
        while (delegate = [enumerator nextObject]) {
            if ([delegate respondsToSelector:selector] && block) block(delegate);
        }
    }else {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSArray *temp = [self.delegates copy];
            NSEnumerator *enumerator = [temp objectEnumerator];
            id<QNCPDeviceDelegate> delegate = nil;
            while (delegate = [enumerator nextObject]) {
                if ([delegate respondsToSelector:selector] && block) block(delegate);
            }
        });
    }
}


@end
